import React, {Component} from 'react';
import PubSub from 'pubsub-js'
import axios from "axios";

import './index.css'

class Details extends Component {

    state = {
        token: null,
        isFirst: true,
        loading: false,
        errorMsg: '',
        keyword: '',
        details: {}
    }

    componentDidMount() {
        // 订阅搜索
        const token = PubSub.subscribe('search', (_, data) => {
            this.setState({
                keyword: data,
                isFirst: false
            })
            // 搜索
            this.onSearch()
        });
        this.setState({token})
    }

    componentWillUnmount() {
        // 取消搜索订阅
        if (this.state.token) {
            PubSub.unsubscribe('search')
        }
    }

    render() {
        const {keyword, isFirst, loading, errorMsg, details} = this.state
        return (
            <div className={'details-container'}>
                {
                    isFirst ? <p>欢迎使用超级搜索</p> :
                        loading ? <p>数据加载中...</p> :
                            errorMsg ? <p style={{color: '#f52443'}}>{errorMsg}</p> :
                                <div>
                                    <h3>{keyword}</h3>
                                    <div className={'details-content'}>
                                        {details.content}
                                    </div>
                                </div>
                }
            </div>
        );
    }

    // 搜索数据
    onSearch = () => {
        const data = {
            api_key: '96aa98a8d4de9ec5',
            type: 'Baidu',
            word: this.state.keyword
        };

        // 判断是否输入查询的内容
        if (!data.word) {
            this.setState({errorMsg: '请输入搜索的内容'})
            return
        }

        // 清空异常信息
        this.setState({errorMsg: ''})
        // 开启加载中
        this.setState({loading: true})
        // 加载数据
        axios.get('/muxiaoguo-api/Baike', {params: data}).then((res) => {
            const {data} = res
            if (data.code === 200) {
                this.setState({details: data.data})
            } else {
                this.setState({errorMsg: '请求异常：' + data.msg})
            }
        }).catch((err) => {
            this.setState({errorMsg: '服务器错误：' + err.message})
        }).finally(() => {
            // 关闭加载
            this.setState({loading: false})
        })
    }
}

export default Details;